import {CartApi} from "../api/index";

export  default {
        namespaced:true,
        state: {list:[], },
        getters:{},
        mutations:{
                init(state,list){
                      state.list=list;
                },
                decrease(state,id){
                        state.list.find(item=>item.id===id).count-=1;
                },
                increase(state,id){
                        state.list.find(item=>item.id===id).count+=1;
                },
                batchRemove(state,ids){
                        ids.forEach(id=>{
                                let i=state.list.findIndex(item=>item.id===id);
                                state.list.splice(i,1);
                                console.log(1)
                        })
                },

        },
        actions:{
               async init({state,commit}){
                        if(state.isInit) return state.list;
                       const list = await  CartApi.getList();
                       commit('init',list);
                       return list;

                },
                async decrease({commit},id){
                        await CartApi.decrease(id);
                        commit('decrease',id);
                },
                async increase({commit},id){
                       await CartApi.increase(id);
                       commit('increase',id);
                },
                async batchRemove({commit},ids){
                       await CartApi.remove({ids});
                       commit('batchRemove',ids)
                },

        },
}